<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button
            v-if="checkBtnAccess('POINT_EXCEL_IMPORT')"
            type="warning"
            size="small"
            @click="$router.push('/import?type=user')"
            >excel导入</el-button
          >
          <el-button
            v-if="checkBtnAccess('POINT_EXCEL_EXPORT')"
            type="danger"
            size="small"
            @click="handleExportExcel"
            >excel导出</el-button
          >
          <el-button type="primary" size="small" @click="handleAddEmployee"
            >新增员工</el-button
          >
        </template>
      </page-tools>

      <el-card v-loading="loading" style="margin-top: 10px">
        <el-table :data="list" border>
          <el-table-column
            type="index"
            :index="indexMethod"
            label="序号"
            sortable
            width="80px"
          />
          <el-table-column prop="staffPhoto" label="头像" sortable>
            <template #default="{ row }">
              <img
                alt=""
                class="staff"
                v-imgerror="errorImg"
                :src="row.staffPhoto || defaultPhoto"
                @click="handleClickCode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" sortable />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column
            :formatter="formatterEmployment"
            prop="formOfEmployment"
            label="聘用形式"
            sortable
          />
          <el-table-column prop="departmentName" label="部门" sortable />
          <el-table-column label="入职时间" sortable>
            <template #default="{ row }">
              {{ row.timeOfEntry | formatTime("YYYY年MM月DD日") }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                :disabled="!checkBtnAccess('POINT_USER_EDIT')"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="handleAssignRole(row.id)"
                >角色</el-button
              >
              <el-button
                :disabled="!checkBtnAccess('POINT_USER_DELETE')"
                type="text"
                size="small"
                @click="deleteItem(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="pagesize"
            :page-sizes="[1, 2, 3, 4, 5]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes, prev, pager, next, jumper"
          >
          </el-pagination>
        </div>
      </el-card>
      <AddEmployee
        :showDialog.sync="isShow"
        @addEmployee="getUserList"
      ></AddEmployee>

      <el-dialog
        title="二维码预览"
        width="400px"
        :visible="showCode"
        :close-on-click-modal="false"
        @close="showCode = false"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <AssignRole
        :showRoleDialog.sync="showRoleDialog"
        :userId="userId"
      ></AssignRole>
    </div>
  </div>
</template>

<script>
import { reqGetUserList, reqDelEmployee } from "@/api/employees";
import AddEmployee from "./components/AddEmployee.vue";
import AssignRole from "./components/AssignRole.vue";
import obj from "@/constant/employees";
import dayjs from "dayjs";
import errorImg from "@/assets/common/bigUserHeader.png";
import QrCode from "qrcode";
export default {
  name: "Employees",
  created() {
    this.getUserList();
  },
  components: { AddEmployee, AssignRole },
  data() {
    return {
      page: 1,
      pagesize: 5,
      list: [],
      total: 0,
      loading: false,
      isShow: false,
      defaultPhoto:
        "https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg",
      errorImg,
      showCode: false,
      showRoleDialog: false,
      userId: "",
    };
  },
  methods: {
    handleAddEmployee() {
      if(!this.checkBtnAccess('POINT_USER_ADD')){
        this.$message.error('请联系管理员添加相关权限')
        return 
      }
      this.isShow = true;
    },
    checkBtnAccess(str) {
      const roles = this.$store.getters.roles;
      if (roles) {
        return roles.points.includes(str);
      } else {
        return false;
      }
    },
    handleAssignRole(id) {
      this.showRoleDialog = true;
      this.userId = id;
    },
    handleClickCode(url) {
      if (!url) return;
      this.showCode = true;
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url);
      });
    },
    async handleExportExcel() {
      // 表头
      const headersArr = [
        "姓名",
        "手机号",
        "入职日期",
        "聘用形式",
        "转正日期",
        "工号",
        "部门",
      ];
      // 中英文对照表
      const headersRelations = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      // 原数据
      const {
        data: { rows },
      } = await reqGetUserList(1, this.total);
      console.log(rows);
      // 多表头
      const multiHeader = [["姓名", "主要信息", "", "", "", "", "部门"]];
      const merges = ["A1:A2", "B1:F1", "G1:G2"];
      const result = this.transOriginToErWei(
        rows,
        headersArr,
        headersRelations
      );
      console.log(result, 768);
      import("@/vendor/Export2Excel").then((excel) => {
        console.log(excel);
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          data: result, // 具体数据 必填
          filename: "员工信息表", // 非必填
          autoWidth: true, // 非必填
          bookType: "xlsx", // 非必填
          multiHeader,
          merges,
        });
      });
    },
    transOriginToErWei(rows, headersArr, headersRelations) {
      const arr = [];
      rows.forEach((item) => {
        const res = [];
        headersArr.forEach((v) => {
          const englishKey = headersRelations[v];
          let val = item[englishKey];
          // ['formOfEmployment'].includes(englishKey)
          if (englishKey === "formOfEmployment") {
            const { hireType } = obj;
            const resObj = hireType.find((i) => i.id === +val);
            val = resObj ? resObj.value : "未知";
          }
          if (["timeOfEntry", "correctionTime"].includes(englishKey)) {
            val = dayjs(val).format("YYYY年MM月DD日");
          }
          res.push(val);
        });
        arr.push(res);
      });
      return arr;
    },
    deleteItem(id) {
      this.$confirm("该操作将永久删除该员工,不可逆,你确定继续么？", "温馨提示")
        .then(async () => {
          const res = await reqDelEmployee(id);
          console.log(res);
          this.$message.success("删除员工成功");
          if (this.list.length === 1 && this.page > 1) {
            this.page--;
          }
          this.getUserList();
        })
        .catch(() => {
          console.log("取消");
        });
    },
    formatterEmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index);
      const arr = obj.hireType;
      const res = arr.find((item) => item.id === +cellValue);
      return res ? res.value : "未知";
    },
    indexMethod(index) {
      return index + 1 + this.pagesize * (this.page - 1);
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getUserList();
    },
    handleSizeChange(val) {
      this.pagesize = val;
      this.page = 1;
      this.getUserList();
    },
    async getUserList() {
      this.loading = true;
      const {
        data: { rows, total },
      } = await reqGetUserList(this.page, this.pagesize);
      this.list = rows;
      this.total = total;
      this.loading = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.employees-container {
  ::v-deep.el-table .cell,
  .el-table--border td:first-child .cell,
  .el-table--border th:first-child .cell {
    text-align: center;
  }
  .el-pagination {
    text-align: end;
  }
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>